//
//  YHDeviceID.m
//  YHKit
//
//  Created by 98du on 2021/11/19.
//

#import "YHDeviceID.h"
#import "YHKeyChainStore.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import <YHConstant/YHConstant+Null.h>

@implementation YHDeviceID

/// 广告标识
+ (void)IDFA:(void (^)(NSString * _Nonnull))block{
    if (@available(iOS 14, *)) {
        // iOS14及以上版本需要先请求权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                block(idfa);
            } else {
                NSLog(@"请在设置-隐私-跟踪中允许App请求跟踪");
                block(@"");
            }
        }];
    } else {
        // iOS14以下版本依然使用老方法
        // 判断在设置-隐私里用户是否打开了广告跟踪
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            block(idfa);
        } else {
            NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
            block(@"");
        }
    }
}
/// 厂商标识
+ (NSString *)IDFV{
    NSString * idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return idfv;
}
/// 存在keychina中的标识
+ (NSString *)UUID{
    NSString * uuidKey = @"deviceUUID";
    NSString * service = @"info";
    NSString * uuid = [YHKeyChainStore stringForKey:uuidKey service:service];
    if(!uuid){
//        CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
//        NSString * cfuuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,cfuuid));
        uuid = [[NSUUID UUID] UUIDString];
        [YHKeyChainStore setString:uuid forKey:uuidKey service:service];
    }
    return uuid;
}

/// 设备标识 IDFA>IDFV>UUID
+ (NSString *)deviceID{
    
    __block NSString * uuid = nil;
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [self IDFA:^(NSString * _Nonnull idfa) {
        uuid = idfa;
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
    if(IsNonNull(uuid)){
        return uuid;
    }
    
    uuid = [self IDFV];
    if(IsNonNull(uuid)){
        return uuid;
    }
    
    uuid = [self UUID];
    return uuid;
}

@end
